package com.example.demo.service.impl;

import com.example.demo.dto.UserLoginDTO;
import com.example.demo.dto.UserLoginResponseDTO;
import com.example.demo.dto.UserRegisterDTO;
import com.example.demo.mapper.UserMapper;
import com.example.demo.mapper.OrganizationMapper;
import com.example.demo.model.User;
import com.example.demo.model.Organization;
import com.example.demo.service.TeacherApprovalService;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import org.json.JSONObject;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrganizationMapper organizationMapper;
    
    @Autowired
    private TeacherApprovalService teacherApprovalService;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public UserLoginResponseDTO login(UserLoginDTO loginDTO) {
        // 根据用户码查询用户
        User user = userMapper.findByUsercode(loginDTO.getUsercode());
        if (user == null) {
            throw new RuntimeException("学号/教师号或密码错误");
        }

        // 验证密码
        if (!user.getPasswordHash().equals(loginDTO.getPassword())) {
            throw new RuntimeException("学号/教师号或密码错误");
        }

        // 检查账号是否激活
        if (!user.getIsActive()) {
            throw new RuntimeException("账号已禁用，请联系管理员");
        }
        
        // 检查教师账号是否已审核通过
        if ("TEACHER".equals(user.getUserType()) && user.getExtraInfo() != null && !user.getExtraInfo().isEmpty()) {
            try {
                JSONObject extraInfo = new JSONObject(user.getExtraInfo());
                String approvalStatus = extraInfo.optString("approval_status", "0");
                
                System.out.println("教师登录 - 用户ID: " + user.getUserId() + 
                                   ", 用户码: " + user.getUsercode() + 
                                   ", 审批状态: " + approvalStatus + 
                                   ", extraInfo: " + user.getExtraInfo());
                
                if ("0".equals(approvalStatus)) {
                    throw new RuntimeException("教师账号正在审核中，请耐心等待");
                } else if ("2".equals(approvalStatus)) {
                    String comment = extraInfo.optString("approval_comment", "未通过审核");
                    throw new RuntimeException("教师账号审核未通过: " + comment);
                }
            } catch (Exception e) {
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                }
                throw new RuntimeException("账号状态异常，请联系管理员");
            }
        }

        // 生成 JWT token
        String token = jwtUtils.generateToken(user.getUserId(), user.getUsercode());
        
        // 转换为响应 DTO
        UserLoginResponseDTO responseDTO = convertToResponseDTO(user);
        responseDTO.setToken(token);
        
        return responseDTO;
    }

    @Override
    @Transactional
    public UserLoginResponseDTO register(UserRegisterDTO registerDTO) {
        // 检查用户码是否已存在
        if (checkUsercodeExists(registerDTO.getUsercode())) {
            throw new RuntimeException("该学号/教师号已被注册");
        }

        // 检查邮箱是否已存在
        if (checkEmailExists(registerDTO.getEmail())) {
            throw new RuntimeException("邮箱已存在");
        }

        // 检查组织是否存在
        Organization org = organizationMapper.findById(registerDTO.getOrgId());
        if (org == null) {
            throw new RuntimeException("组织不存在");
        }

        // 创建额外信息JSON
        JSONObject extraInfo = new JSONObject();
        
        // 根据用户类型添加不同的额外信息
        if ("TEACHER".equals(registerDTO.getUserType())) {
            // 对于教师，用户码就是教师工号
            
            // 所有教师注册后默认为待审核状态
            extraInfo.put("approval_status", "0");  // 0-待审核
            extraInfo.put("approval_comment", "等待管理员审核");
            
            // 处理管理员角色申请
            // 优先使用requestedRole，如果没有再尝试使用adminRole
            String adminRole = null;
            if (registerDTO.getRequestedRole() != null && !registerDTO.getRequestedRole().isEmpty()) {
                adminRole = registerDTO.getRequestedRole();
            } else if (registerDTO.getAdminRole() != null && !registerDTO.getAdminRole().isEmpty()) {
                adminRole = registerDTO.getAdminRole();
            }
            
            if (adminRole != null) {
                extraInfo.put("admin_role", adminRole);
                extraInfo.put("admin_role_status", "0"); // 0-待审核
            }
            
            // 如果前端传来了额外信息，合并到extraInfo中
            if (registerDTO.getExtraInfo() != null && !registerDTO.getExtraInfo().isEmpty()) {
                try {
                    // 解析前端传来的JSON字符串
                    JSONObject frontendExtraInfo = new JSONObject(registerDTO.getExtraInfo());
                    // 遍历并合并字段
                    for (String key : frontendExtraInfo.keySet()) {
                        Object value = frontendExtraInfo.get(key);
                        if (value != null) {
                            extraInfo.put(key, value);
                        }
                    }
                } catch (Exception e) {
                    // 解析失败，忽略额外信息
                    System.err.println("解析extraInfo失败: " + e.getMessage());
                }
            }
        } else if ("STUDENT".equals(registerDTO.getUserType())) {
            // 对于学生，用户码就是学号
            
            // 如果前端传来了额外信息，合并到extraInfo中
            if (registerDTO.getExtraInfo() != null && !registerDTO.getExtraInfo().isEmpty()) {
                try {
                    // 解析前端传来的JSON字符串
                    JSONObject frontendExtraInfo = new JSONObject(registerDTO.getExtraInfo());
                    // 遍历并合并字段
                    for (String key : frontendExtraInfo.keySet()) {
                        Object value = frontendExtraInfo.get(key);
                        if (value != null) {
                            extraInfo.put(key, value);
                        }
                    }
                } catch (Exception e) {
                    // 解析失败，忽略额外信息
                    System.err.println("解析extraInfo失败: " + e.getMessage());
                }
            }
        }

        // 创建用户对象
        User user = new User();
        user.setUsercode(registerDTO.getUsercode());
        user.setPasswordHash(registerDTO.getPassword());
        user.setEmail(registerDTO.getEmail());
        user.setFullName(registerDTO.getFullName());
        user.setUserType(registerDTO.getUserType());
        user.setOrgId(registerDTO.getOrgId());
        user.setExtraInfo(extraInfo.toString());
        user.setIsActive(true);
        
        // 保存用户
        userMapper.insert(user);
        
        // 如果是教师，创建教师审核记录
        if ("TEACHER".equals(registerDTO.getUserType())) {
            // 创建教师审核记录
            teacherApprovalService.createApproval(
                user.getUserId(),
                registerDTO.getRequestedRole(),
                "教师账号注册申请"
            );
        }
        
        // 为学生创建默认角色
        if ("STUDENT".equals(registerDTO.getUserType())) {
            // 可以在这里为学生添加默认权限/角色
        }
        
        // 生成 JWT token
        String token = jwtUtils.generateToken(user.getUserId(), user.getUsercode());
        
        // 转换为响应 DTO
        UserLoginResponseDTO responseDTO = convertToResponseDTO(user);
        responseDTO.setToken(token);
        
        return responseDTO;
    }

    @Override
    public User findById(Integer userId) {
        return userMapper.findById(userId);
    }

    @Override
    public User findByEmail(String email) {
        return userMapper.findByEmail(email);
    }

    @Override
    public List<User> findByOrgId(Integer orgId) {
        return userMapper.findByOrgId(orgId);
    }

    @Override
    public List<User> findByUserType(String userType) {
        return userMapper.findByUserType(userType);
    }

    @Override
    public List<User> findByOrgIdAndUserType(Integer orgId, String userType) {
        return userMapper.findByOrgIdAndUserType(orgId, userType);
    }
    
    @Override
    public List<User> findByOrgTreeAndUserType(Integer orgId, String userType) {
        return userMapper.findByOrgTreeAndUserType(orgId, userType);
    }
    
    @Override
    public List<User> findPendingTeachers() {
        return userMapper.findByApprovalStatus("TEACHER", "0");
    }

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    @Transactional
    public User create(User user) {
        userMapper.insert(user);
        return user;
    }

    @Override
    @Transactional
    public User update(User user) {
        // 获取当前用户信息
        User existingUser = userMapper.findById(user.getUserId());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 更新基本信息
        if (user.getFullName() != null) {
            existingUser.setFullName(user.getFullName());
        }
        
        if (user.getEmail() != null) {
            existingUser.setEmail(user.getEmail());
        }
        
        // 更新组织ID
        if (user.getOrgId() != null) {
            // 验证组织是否存在
            Organization org = organizationMapper.findById(user.getOrgId());
            if (org == null) {
                throw new RuntimeException("组织不存在");
            }
            
            // 学生只能更新为班级组织
            if ("STUDENT".equals(existingUser.getUserType()) && !"CLASS".equals(org.getOrgType())) {
                throw new RuntimeException("学生只能选择班级作为组织");
            }
            
            // 更新组织ID
            existingUser.setOrgId(user.getOrgId());
        }
        
        // 更新密码（如果有）
        if (user.getPasswordHash() != null && !user.getPasswordHash().isEmpty()) {
            existingUser.setPasswordHash(user.getPasswordHash());
        }
        
        // 更新额外信息（如果有）
        if (user.getExtraInfo() != null && !user.getExtraInfo().isEmpty()) {
            try {
                // 如果已有额外信息，则合并
                if (existingUser.getExtraInfo() != null && !existingUser.getExtraInfo().isEmpty()) {
                    JSONObject existingExtraInfo = new JSONObject(existingUser.getExtraInfo());
                    JSONObject newExtraInfo = new JSONObject(user.getExtraInfo());
                    
                    // 合并两个JSON对象
                    for (String key : newExtraInfo.keySet()) {
                        existingExtraInfo.put(key, newExtraInfo.get(key));
                    }
                    
                    existingUser.setExtraInfo(existingExtraInfo.toString());
                } else {
                    existingUser.setExtraInfo(user.getExtraInfo());
                }
            } catch (Exception e) {
                throw new RuntimeException("额外信息格式错误");
            }
        }
        
        // 执行更新
        userMapper.update(existingUser);
        return existingUser;
    }
    
    @Override
    @Transactional
    public boolean approveTeacher(Integer userId, Integer approverId, boolean isApproved, String comment) {
        User teacher = userMapper.findById(userId);
        if (teacher == null || !"TEACHER".equals(teacher.getUserType())) {
            throw new RuntimeException("用户不存在或不是教师账号");
        }
        
        try {
            JSONObject extraInfo = new JSONObject(teacher.getExtraInfo());
            extraInfo.put("approval_status", isApproved ? "1" : "2");
            extraInfo.put("approval_comment", comment);
            extraInfo.put("approver_id", approverId);
            
            teacher.setExtraInfo(extraInfo.toString());
            userMapper.update(teacher);
            
            return true;
        } catch (Exception e) {
            throw new RuntimeException("处理教师审批失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean deleteById(Integer userId) {
        // 首先删除与用户相关的记录
        try {
            // 删除与用户相关的教师审批记录
            jdbcTemplate.update("DELETE FROM teacher_approval WHERE user_id = ?", userId);
            
            // 删除与用户相关的测试记录
            jdbcTemplate.update("DELETE FROM test_records WHERE user_id = ?", userId);
            
            // 删除用户
            return userMapper.deleteById(userId) > 0;
        } catch (Exception e) {
            throw new RuntimeException("删除用户失败: " + e.getMessage());
        }
    }

    @Override
    public boolean checkEmailExists(String email) {
        return userMapper.findByEmail(email) != null;
    }

    @Override
    public boolean checkUsercodeExists(String usercode) {
        return userMapper.findByUsercode(usercode) != null;
    }

    @Override
    @Transactional
    public boolean changePassword(Integer userId, String oldPassword, String newPassword) {
        // 查询用户
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证旧密码
        if (!user.getPasswordHash().equals(oldPassword)) {
            throw new RuntimeException("旧密码错误");
        }
        
        // 更新密码
        user.setPasswordHash(newPassword);
        userMapper.update(user);
        
        return true;
    }

    @Override
    @Transactional
    public boolean setAdminRole(Integer userId, String adminRole) {
        // 查询用户
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查用户是否为教师
        if (!"TEACHER".equals(user.getUserType())) {
            throw new RuntimeException("只有教师用户才能设置管理员角色");
        }
        
        try {
            // 解析额外信息
            JSONObject extraInfo;
            if (user.getExtraInfo() != null && !user.getExtraInfo().isEmpty()) {
                extraInfo = new JSONObject(user.getExtraInfo());
            } else {
                extraInfo = new JSONObject();
            }
            
            // 更新管理员角色
            if (adminRole != null && !adminRole.isEmpty()) {
                extraInfo.put("admin_role", adminRole);
                extraInfo.put("admin_role_status", "1"); // 1-已通过
            } else {
                // 如果角色为空，则移除管理员角色
                if (extraInfo.has("admin_role")) {
                    extraInfo.remove("admin_role");
                }
                if (extraInfo.has("admin_role_status")) {
                    extraInfo.remove("admin_role_status");
                }
            }
            
            // 更新用户额外信息
            user.setExtraInfo(extraInfo.toString());
            userMapper.update(user);
            
            return true;
        } catch (Exception e) {
            throw new RuntimeException("设置管理员角色失败: " + e.getMessage());
        }
    }

    @Override
    public UserLoginResponseDTO convertToResponseDTO(User user) {
        UserLoginResponseDTO responseDTO = new UserLoginResponseDTO();
        responseDTO.setUserId(user.getUserId());
        responseDTO.setUsercode(user.getUsercode());
        responseDTO.setEmail(user.getEmail());
        responseDTO.setFullName(user.getFullName());
        responseDTO.setIsActive(user.getIsActive());
        responseDTO.setUserType(user.getUserType());
        responseDTO.setOrgId(user.getOrgId());
        
        // 获取组织信息
        Organization org = organizationMapper.findById(user.getOrgId());
        if (org != null) {
            responseDTO.setOrgName(org.getName());
            responseDTO.setOrgType(org.getOrgType());
            
            // 设置用户所属的学院和系信息
            if ("CLASS".equals(org.getOrgType())) {
                // 如果用户所属组织是班级，查找其所属的系和学院
                Organization major = null;
                Organization department = null;
                
                // 获取所属系
                if (org.getParentId() != null) {
                    major = organizationMapper.findById(org.getParentId());
                    responseDTO.setMajorName(major != null ? major.getName() : null);
                    
                    // 获取所属学院
                    if (major != null && major.getParentId() != null) {
                        department = organizationMapper.findById(major.getParentId());
                        responseDTO.setDepartmentName(department != null ? department.getName() : null);
                    }
                }
            } else if ("MAJOR".equals(org.getOrgType())) {
                // 如果用户所属组织是系，查找其所属的学院
                responseDTO.setMajorName(org.getName());
                
                if (org.getParentId() != null) {
                    Organization department = organizationMapper.findById(org.getParentId());
                    responseDTO.setDepartmentName(department != null ? department.getName() : null);
                }
            } else if ("DEPARTMENT".equals(org.getOrgType())) {
                // 如果用户所属组织是学院
                responseDTO.setDepartmentName(org.getName());
            }
        }
        
        // 设置用户特定信息
        try {
            if (user.getExtraInfo() != null && !user.getExtraInfo().isEmpty()) {
                responseDTO.setExtraInfo(user.getExtraInfo());
                
                JSONObject extraInfo = new JSONObject(user.getExtraInfo());
                
                if ("TEACHER".equals(user.getUserType())) {
                    UserLoginResponseDTO.TeacherInfo teacherInfo = new UserLoginResponseDTO.TeacherInfo();
                    teacherInfo.setUserId(user.getUserId());
                    teacherInfo.setTitle(extraInfo.optString("title", ""));
                    teacherInfo.setAdminRole(extraInfo.optString("admin_role", ""));
                    teacherInfo.setAdminRoleStatus(extraInfo.optString("admin_role_status", "0"));
                    teacherInfo.setApprovalStatus(extraInfo.optString("approval_status", "0"));
                    responseDTO.setTeacherInfo(teacherInfo);
                    
                    // 设置消息提示
                    String approvalStatus = extraInfo.optString("approval_status", "0");
                    if ("0".equals(approvalStatus)) {
                        responseDTO.setMessage("教师账号审核中");
                    } else if ("2".equals(approvalStatus)) {
                        responseDTO.setMessage("教师账号审核未通过: " + extraInfo.optString("approval_comment", ""));
                    }
                    
                    // 获取管理员角色
                    String adminRole = extraInfo.optString("admin_role", "");
                    
                    // 根据管理员角色设置管理范围的组织信息
                    if (adminRole != null && !adminRole.isEmpty()) {
                        StringBuilder adminOrgName = new StringBuilder();
                        
                        // 获取当前组织信息
                        Organization currentOrg = organizationMapper.findById(user.getOrgId());
                        
                        if (currentOrg != null) {
                            if ("SCHOOL_ADMIN".equals(adminRole)) {
                                // 校级管理员只显示学校名称
                                Organization school = findSchoolOrganization(currentOrg);
                                if (school != null) {
                                    adminOrgName.append(school.getName());
                                }
                            } else if ("DEPARTMENT_ADMIN".equals(adminRole)) {
                                // 院级管理员显示学校和学院
                                Organization school = findSchoolOrganization(currentOrg);
                                if (school != null) {
                                    adminOrgName.append(school.getName()).append(" - ");
                                }
                                
                                // 如果当前组织是院系，直接使用；否则查找父组织
                                if ("DEPARTMENT".equals(currentOrg.getOrgType())) {
                                    adminOrgName.append(currentOrg.getName());
                                } else {
                                    Organization department = findDepartmentOrganization(currentOrg);
                                    if (department != null) {
                                        adminOrgName.append(department.getName());
                                    }
                                }
                            } else if ("MAJOR_ADMIN".equals(adminRole)) {
                                // 系级管理员显示学校、学院和系
                                Organization school = findSchoolOrganization(currentOrg);
                                if (school != null) {
                                    adminOrgName.append(school.getName()).append(" - ");
                                }
                                
                                Organization department = findDepartmentOrganization(currentOrg);
                                if (department != null) {
                                    adminOrgName.append(department.getName()).append(" - ");
                                }
                                
                                // 如果当前组织是系，直接使用；否则查找父组织
                                if ("MAJOR".equals(currentOrg.getOrgType())) {
                                    adminOrgName.append(currentOrg.getName());
                                } else {
                                    Organization major = findMajorOrganization(currentOrg);
                                    if (major != null) {
                                        adminOrgName.append(major.getName());
                                    }
                                }
                            } else if ("CLASS_ADMIN".equals(adminRole)) {
                                // 班级管理员显示完整的组织层级
                                Organization school = findSchoolOrganization(currentOrg);
                                if (school != null) {
                                    adminOrgName.append(school.getName()).append(" - ");
                                }
                                
                                Organization department = findDepartmentOrganization(currentOrg);
                                if (department != null) {
                                    adminOrgName.append(department.getName()).append(" - ");
                                }
                                
                                Organization major = findMajorOrganization(currentOrg);
                                if (major != null) {
                                    adminOrgName.append(major.getName()).append(" - ");
                                }
                                
                                // 如果当前组织是班级，直接使用
                                if ("CLASS".equals(currentOrg.getOrgType())) {
                                    adminOrgName.append(currentOrg.getName());
                                }
                            }
                        }
                        
                        // 设置管理范围的组织名称
                        if (adminOrgName.length() > 0) {
                            extraInfo.put("admin_org_name", adminOrgName.toString());
                            responseDTO.setExtraInfo(extraInfo.toString());
                        }
                    }
                } else if ("STUDENT".equals(user.getUserType())) {
                    UserLoginResponseDTO.StudentInfo studentInfo = new UserLoginResponseDTO.StudentInfo();
                    studentInfo.setUserId(user.getUserId());
                    responseDTO.setStudentInfo(studentInfo);
                }
            }
        } catch (Exception e) {
            // 忽略解析错误
        }
        
        return responseDTO;
    }

    @Override
    public User findByUsercode(String usercode) {
        return userMapper.findByUsercode(usercode);
    }

    /**
     * 查找学校级别的组织
     */
    private Organization findSchoolOrganization(Organization org) {
        if (org == null) return null;
        
        if ("SCHOOL".equals(org.getOrgType())) {
            return org;
        }
        
        // 向上查找学校级别的组织
        Organization parent = org;
        while (parent != null && !"SCHOOL".equals(parent.getOrgType())) {
            if (parent.getParentId() == null) break;
            parent = organizationMapper.findById(parent.getParentId());
        }
        
        return parent;
    }
    
    /**
     * 查找院系级别的组织
     */
    private Organization findDepartmentOrganization(Organization org) {
        if (org == null) return null;
        
        if ("DEPARTMENT".equals(org.getOrgType())) {
            return org;
        }
        
        // 向上查找院系级别的组织
        Organization parent = org;
        while (parent != null && !"DEPARTMENT".equals(parent.getOrgType())) {
            if (parent.getParentId() == null) break;
            parent = organizationMapper.findById(parent.getParentId());
            if ("SCHOOL".equals(parent.getOrgType())) break; // 如果到达学校级别，停止查找
        }
        
        return "DEPARTMENT".equals(parent.getOrgType()) ? parent : null;
    }
    
    /**
     * 查找系级别的组织
     */
    private Organization findMajorOrganization(Organization org) {
        if (org == null) return null;
        
        if ("MAJOR".equals(org.getOrgType())) {
            return org;
        }
        
        // 向上查找系级别的组织
        Organization parent = org;
        while (parent != null && !"MAJOR".equals(parent.getOrgType())) {
            if (parent.getParentId() == null) break;
            parent = organizationMapper.findById(parent.getParentId());
            if ("DEPARTMENT".equals(parent.getOrgType()) || "SCHOOL".equals(parent.getOrgType())) break; // 如果到达院系或学校级别，停止查找
        }
        
        return "MAJOR".equals(parent.getOrgType()) ? parent : null;
    }
}

